﻿using MicroMq.Helper;
using MicroMq.Models;

using Microsoft.Extensions.DependencyInjection;

using MTP.Serialize;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MicroMq.Services
{
    class PublishSerivce : IHandlerService
    {
        private readonly IServiceProvider serviceProvider;

        private readonly EventWorkService workService;
        public PublishSerivce(IServiceProvider serviceProvider, EventWorkService workService)
        {
            this.serviceProvider = serviceProvider;
            this.workService = workService;
        }

        byte IHandlerService.HandleType => (byte)HandleType.Publish;


        public void Hanlder(PeerConnection connection, ByteReadBuffer readBuffer)
        {
            var manager = serviceProvider.GetService<MqConnectionManager>();
            Publish(manager, readBuffer.ReadUnknownString(), readBuffer.ReadEnd());
        }

        public void Publish(MqConnectionManager manager, string topic, byte[] data)
        {
            var session = manager.Group(topic);
            var buffer = ByteWriteBuffer.Alloc()
                .WriteUnknownString(topic)
                .Write(data)
                .ToBytes();
            if (!session.Has())
            {
                workService.Enqueue(topic, buffer);
                return;
            }
            session.SendAsync(buffer);
        }
    }
}
